package com.saint.farmshop.Mapper.MapperImpl;

import com.saint.farmshop.Entity.Address;
import com.saint.farmshop.Mapper.UserMapper;
import com.saint.farmshop.Entity.User;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户数据访问实现类
 *
 * @author Saint
 * @date 2022/05/21
 */
@Repository
public class UserMapperImpl implements UserMapper {

    @Resource
    MongoTemplate mongoTemplate;

    final String COLLECTION_NAME = "user";

    @Override
    public boolean isRegisted(String openId) {
        Criteria criteria = new Criteria();
        criteria.and("openId").is(openId);
        Query query = new Query(criteria);
        User one = mongoTemplate.findOne(query, User.class, COLLECTION_NAME);
        if (one != null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public User selectUserByOpenId(String openId) {
        Criteria criteria = new Criteria();
        Update update = new Update().set("lastLoginTime", LocalDateTime.now());
        criteria.and("openId").is(openId);
        Query query = new Query(criteria);
        User select = mongoTemplate.findOne(query, User.class, COLLECTION_NAME);
        mongoTemplate.updateFirst(query, update, COLLECTION_NAME);
        return select;
    }

    @Override
    public User insertUser(User user) {
        user.setBirthDay(LocalDate.now());
        user.setStatus(1);
        user.setSex(-1);
        user.setLastLoginTime(LocalDateTime.now());
        user.setEmail("");
        user.setRealName("");
        user.setUserIntroduce("");
        mongoTemplate.insert(user, COLLECTION_NAME);
        return user;
    }

    @Override
    public void updateUser(User user) {
        mongoTemplate.save(user, COLLECTION_NAME);

    }

    @Override
    public List<User> getList() {
        return mongoTemplate.findAll(User.class,COLLECTION_NAME);
    }

    @Override
    public boolean addAddress(Address address, String openId) {
        User user = selectUserByOpenId(openId);
        List<Address> addresses = new ArrayList<>();
        if(user.getAddress() != null){
            addresses.addAll(user.getAddress());
        }
        addresses.add(address);
        Update update = new Update().set("address",addresses);
        Criteria criteria = Criteria.where("openId").is(openId);
        Query query = new Query(criteria);
        if (mongoTemplate.updateFirst(query,update, User.class,COLLECTION_NAME) == null) {
            return false;
        }
        else{
            return true;
        }
    }
}
